package cn.com.scitc.licenseplateback.md5;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class MD5Util {

    /**
     * 加密方法
     *
     * @param str
     * @return
     */
    private static String MD5(String str) {
        return DigestUtils.md5Hex(str);
    }

    /**
     * 加固定盐
     */
    private static String SALT = "K3QnVla4t8Bd1";

    /**
     * 将用户输入的密码与盐进行拼接后进行MD5加密
     *
     * @param inputPass 原始密码
     * @return 加盐MD5
     */
    private static String INPUTPASSANDSALT(String inputPass) {
        String str = SALT.charAt(2) + SALT.charAt(5) + inputPass + SALT.charAt(0) + SALT.charAt(3);
        return MD5(str);
    }

    /**
     * 将用户的密码进行二次加密
     *
     * @param formPass 加盐MD5密码
     * @param salt     随机盐
     * @return 加密密码
     */
    private static String FORMPASSTODBPASS(String formPass, String salt) {
        String str = salt.charAt(1) + salt.charAt(4) + salt.charAt(9) + formPass + salt.charAt(2) + salt.charAt(6) + salt.charAt(7);
        return MD5(str);
    }

    /**
     * 随机盐
     *
     * @return
     */
    public String randomSalt() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int number = random.nextInt(3);
            switch (number) {
                case 0:
                    sb.append((char) (random.nextInt(57 - 48) + 48));
                    break;
                case 1:
                    sb.append((char) (random.nextInt(122 - 97) + 97));
                    break;
                case 2:
                    sb.append((char) (random.nextInt(90 - 65) + 65));
                    break;

            }
        }
        return sb.toString();
    }


    public String FINALPASS(String inputPass, String salt) {
        String inputpassandsalt = INPUTPASSANDSALT(inputPass);

        String dbpass = FORMPASSTODBPASS(inputpassandsalt, salt);

        return dbpass;
    }


}
